package common

import (
	"github.com/asim/go-micro/plugins/config/source/consul/v3"
	consul_registry "github.com/asim/go-micro/plugins/registry/consul/v3"
	"github.com/asim/go-micro/v3/config"
	"github.com/asim/go-micro/v3/registry"
	"github.com/zw2582/ginlib"
	"go.uber.org/zap"
)

var (
	microConsulConfig config.Config
)

//InitConsulConfig 初始化consul配置中心，配置中心的参数来源于ini文件，所以应该先执行ginlib.InitIni()
func InitConsulConfig() {
	if microConsulConfig != nil {
		return
	}

	host, port, prefix := getConsulConfigFromIni()
	ginlib.Logger.Info("consul connection:", zap.String("host", host), zap.String("port", port), zap.String("prefix", prefix))
	//consul动态配置
	configSource := consul.NewSource(
		consul.WithAddress(host+":"+port),
		consul.WithPrefix(prefix),
		consul.StripPrefix(true),
	)

	t, err := config.NewConfig()
	if err != nil {
		panic(err)
	}
	t.Load(configSource)

	microConsulConfig = t
}

func CreateRegistryFromConsul() registry.Registry {
	host, port, _ := getConsulConfigFromIni()
	r := consul_registry.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{host + ":" + port}
	})

	return r
}

func getConsulConfigFromIni() (host, port, prefix string) {
	host = ginlib.Ini_Str("consul.host", "127.0.0.1")
	port = ginlib.Ini_Str("consul.port", "127.0.0.1")
	prefix = ginlib.Ini_Str("consul.prefix", "")
	return
}
